import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx/xlsx.mjs'
import OSS from 'ali-oss';


export function randomNum(min, max) {
  if (max - min >= 1) {
    const diff = max - min;
    return Math.floor(Math.random() * diff) + min;
  }
  return 'min必须小于max';
}

// 生成随机字符串，字符串中既有字母也有数字
export function randomStr(length) {
  // 从第2位开始截取
  let endNum = 10
  if (length) {
    endNum = (2 + length)
  }
  return Math.random().toString(36).slice(2, endNum)
}
// 生成只有字母的随机字符串
export function randomChar(length = 6) {
  // 从第2位定位
  let arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  let idvalue = '';

  for (let i = 0; i < length; i++) {
    idvalue += arr[Math.floor(Math.random() * 52)];
  }
  return idvalue;
}

// 生成唯一订单号
export function tradeNo() {
  const now = new Date();
  const year = now.getFullYear();
  let month = now.getMonth() + 1;
  let day = now.getDate();
  let hour = now.getHours();
  let minutes = now.getMinutes();
  let seconds = now.getSeconds();
  String(month).length < 2 ? (month = Number('0' + month)) : month;
  String(day).length < 2 ? (day = Number('0' + day)) : day;
  String(hour).length < 2 ? (hour = Number('0' + hour)) : hour;
  String(minutes).length < 2 ? (minutes = Number('0' + minutes)) : minutes;
  String(seconds).length < 2 ? (seconds = Number('0' + seconds)) : seconds;
  const yyyyMMddHHmmss = `${year}${month}${day}${hour}${minutes}${seconds}`;
  return yyyyMMddHHmmss + '_' + Math.random().toString(36).substr(2, 9);
}

// 显示信息
export function MyMessage(msgObj) {
  ElMessage.closeAll()
  ElMessage(msgObj)
}

function initOss() {
  const client = new OSS({
    // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
    region: 'oss-cn-beijing',
    accessKeyId: 'LTAI5t7PhmCpbAr3au3yKWZK',
    accessKeySecret: 'TMN1AtbGse8oDzHrWX17m70oX010DC',
    // 填写Bucket名称。
    bucket: 'poi-address',
    secure: true
  });
  // console.log('client:', client)
  return client
}

async function ossUpload(fileName, blobData) {
  let client = initOss()
  return new Promise(async (resolve, reject) => {
    let res = await client.put(fileName, blobData, {
      headers: {
        'Content-Disposition': 'attachment'
      }
    });
    if (res.res.status === 200) {
      resolve(res.url)
    } else {
      resolve(null)
    }
  })

}
// 下载有关函数
// 将表格sheet数据转成blob地址

export async function sheet2blobUrl(sheet, fileName) {
  let sheetName = 'sheet'
  var workbook = {
    SheetNames: [sheetName],
    Sheets: {}
  }
  workbook.Sheets[sheetName] = sheet
  // 生成excel的配置项
  var wopts = {
    bookType: 'xlsx', // 要生成的文件类型
    bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
    type: 'binary'
  }
  var wbout = XLSX.write(workbook, wopts)
  var blob = new Blob([s2ab(wbout)], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  // 字符串转ArrayBuffer
  function s2ab(s) {
    var buf = new ArrayBuffer(s.length)
    var view = new Uint8Array(buf)
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
    return buf
  }
  let url = URL.createObjectURL(blob)
  if (isMobile()) {
    console.log('fileName:', fileName)
    url = await ossUpload(fileName, blob)
  }
  // console.log('url:', url)
  return url
}

// 下载文件
async function downFile(url, fileName) {

  const el = document.createElement('a')
  el.style.display = 'none'
  el.setAttribute('target', '_blank')

  el.href = url
  el.download = fileName
  document.body.appendChild(el)
  el.click()
  document.body.removeChild(el)
  window.URL.revokeObjectURL(url)
}

// 下载数据
export async function startDownLoadDataFn(workSheet, fileName) {
  const url = await sheet2blobUrl(workSheet, fileName)
  // console.log('download url:', url)
  downFile(url, fileName)
}

// xlsxData 二维数组
/**
 * xlsxData [[姓名,电话],['aa','13288214456']]
 * @param {*} xlsxData 
 */
export function downLoadExcelFile(xlsxData, downloadFileName) {

  // 这个不能放下面，否则显示不出来数据
  let worksheet = XLSX.utils.aoa_to_sheet(xlsxData)
  let nowStr = getNowStr()
  downloadFileName = downloadFileName + '_' + nowStr + '.xlsx'
  startDownLoadDataFn(worksheet, downloadFileName)
}


// xlsxData 二维数组
/**
 * xlsxData [[姓名,电话],['aa','13288214456']]
 * @param {*} xlsxData 
 */
export async function downloadCsvFile(xlsxData, downloadFileName) {
  // csv文件需要对电话和邮编特殊处理，避免电话被科学计数法，避免以0开头的邮编被删0
  // 电话号码 index固定为1，邮编index固定为最后一位
  let strList = xlsxData.map(item => {
    item[1] = '="' + item[1] + '"'
    item[item.length - 1] = '="' + item[item.length - 1] + '"'
    return item.join(',')
  })
  let str = strList.join('\n')
  let blob = new Blob(["\uFEFF" + str], {
    type: 'text/csv;charset=utf-8',
  });
  let nowStr = getNowStr()
  downloadFileName = downloadFileName + '_' + nowStr + '.csv'

  let downLoadUrl = URL.createObjectURL(blob);
  if (isMobile()) {
    downLoadUrl = await ossUpload(downloadFileName, blob)
  }
  let downloadLink = document.createElement("a");
  downloadLink.href = downLoadUrl
  downloadLink.download = downloadFileName;
  downloadLink.click();

}
/**
 * targetList [
 *  {
      "_id": "630346a01bd3b63b54b18101",
      "key": "115.0991,32.128144",
      "proName": "河南省",
      "cityName": "信阳市",
      "countryName": "潢川县",
      "address": "潢川开发区",
      "communityName": "尚景花园",
      "lon": "115.0991",
      "lat": "32.128144",
      "__v": 0,
      "doorNum": "4号楼1单元603号",
      "userName": "阮咏辰",
      "phone": "14542145180",
      "zipCode": "464000"
    }
 * ]
  downloadConfig
  {
    type:'excel',
    whetherSplitAddr:'0',
    txtAddrCont:[], 用户选择的数据 ['手机','姓名']
    splitChar:' ',
  }
 * @param {*} targetList 
 * @param {*} downloadFileName 
 */
export const addrKeyNameObj = {
  '姓名': 'userName',
  '手机': 'phone',
  '完整地址': 'comAddress',
  '邮编': 'zipCode',
  '省': 'proName',
  '市': 'cityName',
  '区县': 'countryName',
  '街道': 'townName',
  '路': 'roadName',
  '小区名': 'communityName',
  '详细地址': 'address',
  '区县+详细地址': 'countryAndAddress'
}
export async function downloadTxtFile(targetList, downloadFileName, downloadConfig) {
  if (downloadConfig.txtAddrCont.length === 0) {
    ElMessage({
      type: 'error',
      message: '下载项不能为空，请勾选'
    })
    return
  }
  let keySeqList = downloadConfig.txtAddrCont.map(item => {
    return addrKeyNameObj[item]
  })
  let splitChar = downloadConfig.splitChar.trim()
  if (!splitChar) {
    splitChar = ' '
  }
  let txtSeqData = targetList.map(item => {
    let needData = []
    keySeqList.forEach(key => {
      needData.push(item[key])
    });
    return needData.join(splitChar)
  })
  let content = txtSeqData.join('\r\n\r\n')
  let blob = new Blob([content], {
    type: 'text/plain;charset=utf-8',
  });
  let nowStr = getNowStr()
  downloadFileName = downloadFileName + (txtSeqData.length) + '_' + nowStr + '.txt'
  let downLoadUrl = URL.createObjectURL(blob)
  if (isMobile()) {
    downLoadUrl = await ossUpload(downloadFileName, blob)
  }

  let downloadLink = document.createElement("a");
  downloadLink.href = downLoadUrl;
  downloadLink.download = downloadFileName;
  downloadLink.click();
}


export async function downloadTxtFileByContentList(contentList, downloadFileName, nNum = 2) {
  let splitChar = '\r\n'
  if (nNum === 2) {
    splitChar = '\r\n\r\n'
  }
  let content = contentList.join(splitChar)
  let blob = new Blob([content], {
    type: 'text/plain;charset=utf-8',
  });
  let nowStr = getNowStr()
  downloadFileName = downloadFileName + '_' + nowStr + '.txt'
  let downLoadUrl = URL.createObjectURL(blob)
  if (isMobile()) {
    downLoadUrl = await ossUpload(downloadFileName, blob)
  }

  let downloadLink = document.createElement("a");
  downloadLink.href = downLoadUrl;
  downloadLink.download = downloadFileName;
  downloadLink.click();
}

export function isMobile() {
  let flag = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
  return flag;
}

export function getTodayStr() {
  let date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  if (month < 10) {
    month = '0' + month
  }

  if (day < 10) {
    day = '0' + day
  }
  return year + '-' + month + '-' + day
}

export function getNowStr() {
  let date = new Date()
  // let year = date.getFullYear()
  // let month = date.getMonth() + 1
  let day = date.getDate()
  return String(day) + '日' + date.getHours() + '点' + String(date.getMinutes()) + '分' + String(date.getSeconds()) + '秒'
}
function getRoomUnit() {
  const num = randomNum(0, 3);
  if (num === 0) {
    return '号';
  } else if (num === 1) {
    return '室';
  } else if (num === 2) {
    return '';
  }
  return '';
}


// 生成随机单元号
export function randomFullUnitNum() {
  const bUnit = Math.random() > 0.5 ? '号楼' : '栋';
  return randomNum(1, 28) + bUnit + randomNum(1, 4) + '单元' + randomNum(1, 28) + '0' + randomNum(1, 4) + getRoomUnit();
}

// 判断是不是微信

export function needOuterBrowser() {
  let ua = navigator.userAgent;
  if (/micromessenger|Alipay/i.test(ua) && isMobile()) {
    // 微信
    return true;
  }
  return false
}


export function isInWxBrowser(){
  let ua = navigator.userAgent;
  if (/micromessenger/i.test(ua)) {
    // 微信
    return true;
  }
  return false
}

export function removeRedundancy(str) {
  if (/(\d+)附近/.test(str)) {
    str = str.replace(/(\d+)附近/, '$1号')
  }
  if (/交叉路?口/.test(str)) {
    str = str.replace(/(.*交叉路?口).*/, '$1')
  }
  if (/交汇处/.test(str)) {
    str = str.replace(/(.*交汇处).*/, '$1')
  }

  return str.replace(/\(.*|（.*|附近|约?\d+米.*|(?:\d+\-|[a-zA-Z]+)?\d+$|^[\da-zA-Z]+.*|undefined|.+、.*|\d+$|）/g, '')
}

export function removeBracket(str) {
  return str.replace(/\(.*?\)|（.*?）/g, '')
}

//清除所有cookie函数
export function clearAllCookie () {
  var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
  if (keys) {
    for (var i = keys.length; i--;)
      document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
  }
}

// 是不是直辖市
export function isZxPro (proName) {
  return /北京|上海|天津|重庆/.test(proName)
}

export function convertCommunityDataToExpressData (communityData) {
  return communityData.map(item => {
    let pcc = ''
    if (isZxPro(item.proName)) {
      pcc = item.cityName + item.countryName
    } else {
      pcc = item.proName + item.cityName + item.countryName
    }

    let roadUnitName = /上海/.test(item.proName) ? '弄' : '号'

    let completeAddress = ''
    let address = ''
    if (!item.poiType || item.poiType === 'community' || item.poiType === 'communitystreet') {
      // 小区数据
      let roadNum = item.roadNum ? item.roadNum + roadUnitName : ''
      address = item.roadName + roadNum + item.communityName + item.doorNum
      completeAddress = pcc + (item.townName || '') + (item.roadName || '') + roadNum + item.communityName + item.doorNum
    } else {
      // 四个直辖市,4个直辖市地址里带有省市区，其他省份没有,先replace，再拼接是为了预防万一
      address = item.address.replace(pcc, '') + item.communityName
      completeAddress = pcc + address
    }

    return {
      proName: item.proName,
      cityName: item.cityName,
      countryName: item.countryName,
      townName: item.townName,
      userName: item.userName,
      phone: item.phone,
      address,
      oAddress:item.address,
      zipCode: item.zipCode,
      comAddress: completeAddress,
      communityName:item.communityName,
      doorNum:item.doorNum
    }
  })

}

export function timestampToTime(timestamp) {
  // 将时间戳转换为Date对象
  const date = new Date(timestamp);

  // 获取年、月、日、时、分、秒
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以需要+1
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');

  // 返回格式化的日期时间字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export function fileToBase64(file, callback) {
  
  // 创建一个FileReader对象
  const reader = new FileReader();
  
  // 监听load事件，当文件读取完成后触发
  reader.onload = function(e) {
      // 将文件内容转换为base64编码
      const base64Encoded = e.target.result;
      // 调用回调函数，传入base64编码的字符串
      callback(base64Encoded);
  };
  
  // 监听error事件，处理读取文件时的错误
  reader.onerror = function(e) {
      console.error('Error reading file', e);
  };
  
  // 读取文件，将其转换为DataURL（Data URL代表一个文件资源，以base64编码）
  reader.readAsDataURL(file);
}